<template>
  <div class="search">
    <el-input
      v-model="form.id"
      placeholder="请输入用户id"
      style="width: 250px; margin-right: 10px"
      size="small"
    ></el-input>
    <el-button type="primary" size="small" @click="search">搜索</el-button>
    <el-button type="success" size="small" @click="insertUser">用户新增</el-button>
  </div>
  <div style="background: #fff; padding: 10px">
    <el-table :data="tableData" style="width: 100%" height="450" size="small">
      <el-table-column label="头像">
        <template #default="scope">
          <el-avatar :size="35" :src="`http://localhost:8080/image/${scope.row.avatar}`">{{
            scope.row.nickname
          }}</el-avatar>
        </template>
      </el-table-column>
      <el-table-column type="index" label="编号" width="100" />
      <el-table-column prop="username" label="账号" />
      <el-table-column prop="nickname" label="昵称" />
      <el-table-column label="创建时间">
        <template #default="scope">
          <div>{{ titleUtil.formatDateToYYYYMMDD(scope.row.createTime) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="上一次登录">
        <template #default="scope">
          <div>{{ titleUtil.formatDateToYYYYMMDD(scope.row.loginTime) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="是否禁用">
        <template #default="scope">
          <el-tag :type="scope.row.isDelete === 0 ? 'success' : 'danger'">{{
            scope.row.isDelete === 0 ? '否' : '是'
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button size="small" type="warning" @click="limitUser(scope.row)">禁用</el-button>
          <el-button size="small" type="danger" @click="deleteUser(scope.row)">删除</el-button>
          <el-button size="small" type="success" @click="openUser(scope.row)">解除禁用</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <AddUser ref="addUser" @insert-user="handlerAdd"></AddUser>
</template>

<script setup>
import request from '@/util/request'
import { onMounted, reactive, ref } from 'vue'
import AddUser from '@/components/AddUser.vue'
import { ElMessage, ElNotification, ElMessageBox } from 'element-plus'
import titleUtil from '@/util/titleUtil'

const tableData = ref([])
const form = reactive({
  id: null
})

const addUser = ref()

const search = () => {
  if (form.id === null) {
    ElMessage.warning('搜索内容不能为空')
    return
  }
  getUsers(form.id)
}

const insertUser = () => {
  addUser.value.open()
}

const handlerAdd = () => {
  getUsers(0)
}

const getUsers = (id) => {
  request
    .get(`/admin/user/list?id=${id}`)
    .then((res) => {
      console.log('获取的用户数据', res.data)
      tableData.value = res.data
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        // ElMessage.error('出错了', err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}

// 用户封禁
const limitUser = (user) => {
console.log(user)
  if(user.isDelete===1){
    ElNotification.warning('抱歉，当前用户已封禁')
    return
  }
  ElMessageBox.confirm('确定要封禁当前用户吗?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      let ws = new WebSocket(`ws://localhost:8080/socket/${user.id}`)
      ws.onopen = () => {}
      request
        .get(`/admin/user/ban?id=${user.id}`)
        .then((res) => {
          getUsers(0)
          ElMessage.success('禁用成功')
          let ws = new WebSocket(`ws://localhost:8080/socket/${user.id}`)
          ws.onopen = () => {
            ws.send(JSON.stringify("封禁通知：抱歉，当前账号被封禁"))
          }
        })
        .catch((err) => {
          if (err.response) {
            console.error(err.message)
            // ElMessage.error('出错了', err.message)
            ElNotification({
              title: 'Error',
              message: err.message,
              type: 'error'
            })
          } else {
            ElNotification({
              title: 'Error',
              message: '网络错误',
              type: 'error'
            })
          }
        })
    })
    .catch(() => {})
}

const openUser = (user) => {
  if(user.isDelete===0){
    ElNotification.warning('抱歉，当前用户为正常')
    return
  }
  ElMessageBox.confirm('确定解禁当前用户吗?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      request
        .get(`/admin/user/openBan?id=${user.id}`)
        .then((res) => {
          console.log('获取成功：', res)
          ElMessage.success('操作成功')
          getUsers(0)
        })
        .catch((err) => {
          if (err.response) {
            console.error(err.message)
            ElNotification({
              title: 'Error',
              message: err.message,
              type: 'error'
            })
          } else {
            ElNotification({
              title: 'Error',
              message: '网络错误',
              type: 'error'
            })
          }
        })
    })
    .catch(() => {})
}

const deleteUser = (user) => {
  ElMessageBox.confirm('确定删除当前用户吗?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      request
        .get(`/admin/user/delete?id=${user.id}`)
        .then((res) => {
          ElMessage.success('删除成功')
          getUsers(0)
        })
        .catch((err) => {
          if (err.response) {
            console.error(err.message)
            // ElMessage.error('出错了', err.message)
            ElNotification({
              title: 'Error',
              message: err.message,
              type: 'error'
            })
          } else {
            ElNotification({
              title: 'Error',
              message: '网络错误',
              type: 'error'
            })
          }
        })
    })
    .catch(() => {})
}

onMounted(() => {
  getUsers(0)
})
</script>

<style scoped>
.search {
  width: calc(100vw - 210px);
  background: #fff;
  height: 50px;
  margin-bottom: 10px;
  padding: 5px;
}
</style>
